package com.edu.framework.websocket.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.edu.common.utils.LogUtils;
import com.edu.common.utils.file.FileTypeUtils;
import com.edu.framework.websocket.WebSocketHolder;
import com.edu.framework.websocket.assemble.message.MessageAssemble;
import com.edu.framework.websocket.assemble.message.TriggerMsgEngine;
import com.edu.framework.websocket.message.base.Message;
import com.edu.framework.websocket.message.base.Response;
import com.edu.framework.websocket.message.highlights.HighlightsRequest;
import com.edu.framework.websocket.message.highlights.HighlightsVO;
import com.edu.system.domain.FileInfo;
import com.edu.system.domain.THighlights;
import com.edu.system.service.ITHighlightsService;
import com.edu.system.service.ITPublishClassService;
import com.edu.system.service.ITTerminalService;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @program: xxxx
 * @description:
 * @author: zlh
 * @create: 2024-01-06 18:20
 **/
@Slf4j
@Component
public class HighlighsService implements MessageAssemble {

  @Resource
  private ITPublishClassService publishClassService;
  @Resource
  private ITHighlightsService highlightsService;
  @Resource
  private ITTerminalService itTerminalService;
  @Value("${image.host}")
  private String imageHost;

  // 通知// 1通知 2校园风采
  public static final Integer PUBLISH_CLASS_TYPE=2;
  private List<Long> highIds;

  public Response<List<HighlightsVO>> getHighlightsVOS(Long roomId) {
    if (roomId == null){
      return null;
    }
    List<Long> ids = publishClassService.queryIdsByRoomId(roomId, PUBLISH_CLASS_TYPE);
    if (CollectionUtils.isEmpty(ids)){
      return Response.ok(HighlightsRequest.TYPE, HighlightsRequest.RESP_KEY, new ArrayList<>());
    }
    List<THighlights> tHighlights = highlightsService.liveListByIds(ids);

//    String ip = "http://" + LogUtils.getLocalHostIp();
    List<HighlightsVO> collect = tHighlights
        .stream()
        .map(THighlights::getFilePath)
        .filter(StrUtil::isNotBlank)
        .map(a -> JSONArray.parseArray(a, FileInfo.class))
        .flatMap(Collection::stream)
        .map(b -> HighlightsVO.builder()
            .uid(b.getUid())
            .type(this.getFileType(b.getUrl()))
            .src(LogUtils.mergeHost(imageHost, b.getUrl()))
            .imageSrc(StrUtil.isNotBlank(b.getCoverUrl()) ? LogUtils.mergeHost(imageHost, b.getCoverUrl()) : null)
            .build()
        ).collect(Collectors.toList());

    highIds = tHighlights.stream().map(THighlights::getId).collect(Collectors.toList());
    return Response.ok(HighlightsRequest.TYPE, HighlightsRequest.RESP_KEY, collect);
  }

  private String getFileType(String fileName){
    String fileType = FileTypeUtils.getFileType(fileName);
    if (fileType.equals("mp4")){
      return "video";
    } else {
      return "image";
    }
  }


  /**
   * 下发消息
   * @param classIds
   * @throws IOException
   */
  public void pushMsg(List<Long> classIds) {
    Map<String, Long> codeMapId = itTerminalService.codeIdMapByLocationIds(null, "班牌");

    Function<String, Message> fc = code -> {
      log.info("机器:{}", code);
      Response<List<HighlightsVO>> vo = this.getHighlightsVOS(codeMapId.getOrDefault(code, null));
      log.info("校园风采：{}", JSONObject.toJSONString(vo));
      return vo;
    };
    Consumer<Message> invoke = message -> highlightsService.publishStatusToOn(this.highIds);
    try {
//      WebSocketHolder.broadcastForCode(new ArrayList<>(codeMapId.keySet()), fc, invoke);
      WebSocketHolder.broadcast(fc, invoke);
    } catch (Exception e) {
      log.error("主动下发失败 推送通知", e);
    }
  }

  @Override
  public void buildTrigger(List<Long> firstClassIds) {
    TriggerMsgEngine.addEveryRun(HighlighsService.class.getSimpleName());

//    Date date = new Date();
//    DateTime beginTime = DateUtil.beginOfDay(date);
//    DateTime endTime = DateUtil.endOfDay(date);
//
//    List<THighlights> highlights = highlightsService.queryTodayChangeList();
//    String clsName = HighlighsService.class.getSimpleName();
//    List<MsgCacheDTO> collect = highlights.stream()
//        .flatMap(a -> {
//          List<Long> list = publishClassService.queryClassIdsByTid(a.getId(), PUBLISH_CLASS_TYPE);
//          List<MsgCacheDTO> d = new ArrayList<>();
//          if (a.getStartTime().after(beginTime) && a.getStartTime().before(endTime)) {
//            d.add(MsgCacheDTO.builder().triggerTime(a.getStartTime()).clsName(clsName)
//                .classIds(list).build());
//          }
//          if (a.getEndTime().after(beginTime) && a.getStartTime().before(endTime)) {
//            d.add(MsgCacheDTO.builder().triggerTime(a.getStartTime()).clsName(clsName)
//                .classIds(list).build());
//          }
//          return d.stream();
//        }).collect(Collectors.toList());
//    // 优先下发
//    if (CollectionUtils.isNotEmpty(firstClassIds)){
//      collect.add(MsgCacheDTO.builder().triggerTime(new Date()).clsName(clsName).classIds(firstClassIds).build());
//    }
//    // 装填
//    TriggerMsgEngine.addMsgDate(collect);
  }

}
